package com.hdoit.ares.web.cust.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.RedEnvelopeRecord;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanInfoService;
import com.hdoit.ares.logical.acc.service.IIncomeInfoService;
import com.hdoit.ares.logical.acc.service.IRedEnvelopeRecordService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.app.service.IAppRemindMessageService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeRecordType;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeStatusType;
import com.hdoit.ares.selfcommon.enums.api.AppResponseStatus;
import com.hdoit.ares.selfcommon.enums.cust.AttentionStatus;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.hdoit.ares.selfcommon.enums.order.GoodsMark;
import com.hdoit.ares.selfcommon.jpush.JpushClient;
import com.hdoit.ares.web.wechat.WechatTemplateManager;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.logical.app.model.LoginAuthority;
import com.tennetcn.common.logical.app.service.ILoginAuthorityService;
import com.tennetcn.common.logical.systask.service.ISmsSendService;
import com.tennetcn.common.logical.viewmodel.wechat.WechatOrderGoodsSearch;
import com.tennetcn.common.logical.wechat.model.WechatOrder;
import com.tennetcn.common.logical.wechat.model.WechatOrderGoods;
import com.tennetcn.common.logical.wechat.service.IWechatOrderGoodsService;
import com.tennetcn.common.logical.wechat.service.IWechatOrderService;
import com.tennetcn.common.message.DaoBaseRuntimeException;
import com.tennetcn.common.selfcommon.enums.wechat.WechatOrderStatus;
import com.tennetcn.common.utils.ChineseUtils;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DESedeCoder;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.IPUtils;
import com.tennetcn.common.utils.MD5Utils;
import com.tennetcn.common.utils.RandomUtils;
import com.tennetcn.component.cache.ICached;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;
import com.tennetcn.web.cbase.ApiAuthPassport;


@Controller
@RequestMapping(value = "/api/v1/customerIdenAresApis/",method = { RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value = "/api/v1/customerIdenAresApis/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class CustomerIdenAresApis extends BaseApi{
	
	private ICustomerService customerService;
	private IGoldenBeanInfoService goldenBeanInfoService;
	private IAccountInfoService accountInfoService;
	private ISmsSendService smsSender;
	private IIncomeInfoService incomeInfoService;
	protected ILoginAuthorityService loginAuthorityService;
	private IWechatOrderService wechatOrderService;
	private IWechatOrderGoodsService wechatOrderGoodsService;
	private IAppRemindMessageService appRemindMessageService;
	private IRedEnvelopeRecordService redEnvelopeRecordService;
	private IWithdrawParamService withdrawParamService;

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}

	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	public IRedEnvelopeRecordService getRedEnvelopeRecordService() {
		return redEnvelopeRecordService;
	}

	@Resource
	public void setRedEnvelopeRecordService(IRedEnvelopeRecordService redEnvelopeRecordService) {
		this.redEnvelopeRecordService = redEnvelopeRecordService;
	}

	public IAppRemindMessageService getAppRemindMessageService() {
		return appRemindMessageService;
	}

	@Resource
	public void setAppRemindMessageService(IAppRemindMessageService appRemindMessageService) {
		this.appRemindMessageService = appRemindMessageService;
	}

	public IWechatOrderGoodsService getWechatOrderGoodsService() {
		return wechatOrderGoodsService;
	}
	
	@Resource
	public void setWechatOrderGoodsService(IWechatOrderGoodsService wechatOrderGoodsService) {
		this.wechatOrderGoodsService = wechatOrderGoodsService;
	}
	
	public IWechatOrderService getWechatOrderService() {
		return wechatOrderService;
	}

	@Resource
	public void setWechatOrderService(IWechatOrderService wechatOrderService) {
		this.wechatOrderService = wechatOrderService;
	}
	
	
	
	public ILoginAuthorityService getLoginAuthorityService() {
		return loginAuthorityService;
	}

	@Resource
	public void setLoginAuthorityService(
			ILoginAuthorityService loginAuthorityService) {
		this.loginAuthorityService = loginAuthorityService;
	}
	
	public IIncomeInfoService getIncomeInfoService() {
		return incomeInfoService;
	}

	@Resource
	public void setIncomeInfoService(IIncomeInfoService incomeInfoService) {
		this.incomeInfoService = incomeInfoService;
	}

	public IGoldenBeanInfoService getGoldenBeanInfoService() {
		return goldenBeanInfoService;
	}

	@Resource
	public void setGoldenBeanInfoService(
			IGoldenBeanInfoService goldenBeanInfoService) {
		this.goldenBeanInfoService = goldenBeanInfoService;
	}

	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}

	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	public ISmsSendService getSmsSender() {
		return smsSender;
	}

	@Resource
	public void setSmsSender(ISmsSendService smsSender) {
		this.smsSender = smsSender;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}
	
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	
	private final String sendMessageApi = "sendMessage";
	private final String matchAndLoginApi = "matchAndLogin";
	private final String boundWechatAndLoginApi = "boundWechatAndLogin";
	private final String thirdpartyLoginApi = "thirdpartyLogin";
	private final String boundPhoneAndLoginApi = "boundPhoneAndLogin";
	private final String updateLevelApi = "updateLevel";
	private final String checkInviteCodeApi = "checkInviteCode";
	private final String retrievePasswordApi = "retrievePasswordApi";

	
		
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = sendMessageApi)
	@ApiOperation(notes = sendMessageApi,httpMethod = "POST",value = "发送短信验证码")
	public String sendMessage(String phone,HttpServletRequest request){
		ResponseModel rm = new ResponseModel();
		String ipAddress = IPUtils.getIpAddr(request);
		String verifyCode = smsSender.sendVerifyCode(phone, ipAddress);
	
		if(!StringUtils.isEmpty(verifyCode)){ 
			cached.put(phone, phone);
			cached.put(phone+"verifyCode", verifyCode);
			cached.put(phone+"sendTime", DateUtils.getCurrent());

			rm.setStatus(AppResponseStatus.message_success);
			rm.setMessage("发送成功");
		
		}else{
			rm.setStatus(AppResponseStatus.message_error);
			rm.setMessage("信息发送失败，请重新获取");
		}
		return rm.toJson();
	}

	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = matchAndLoginApi)
	@ApiOperation(notes = matchAndLoginApi,httpMethod = "POST",value = "匹配并且登录")
	public String matchAndLogin(String phone,String code,String deviceId,String deviceName){
		ResponseModel rm = new ResponseModel();
		ICached cached = CommonApplicationContextUtil.getCurrentContext().getBean(ICached.class);
		String matchCode = String.valueOf(cached.get(phone+"verifyCode"));
		String matchPhone = String.valueOf(cached.get(phone));
		Date sendTime = (Date)cached.get(phone+"sendTime");
		
		
		if(sendTime!=null){
			if(DateUtils.getCurrent().getTime()-sendTime.getTime()>5*60*1000){
				rm.setStatus(AppResponseStatus.code_expire);
				rm.setMessage("验证码已过期");
				return rm.toJson();
			}
		}	
		if(!(code.equals(matchCode) && phone.equals(matchPhone))){
			rm.setStatus(AppResponseStatus.code_data_error);
			rm.setMessage("验证码错误");
			return rm.toJson();
		}

		cached.remove(phone+"verifyCode");
		cached.remove(phone+"sendTime");
		
		Customer customer = customerService.queryModelByPhone(phone);
		if(customer==null){
			rm.setStatus(AppResponseStatus.not_bound_wechat);
			rm.setMessage("账户未绑定微信");
			return rm.toJson();
		}else{
			if(StringUtils.isEmpty(customer.getUnionId())||StringUtils.isEmpty(customer.getAppOpenId())){
				rm.setStatus(AppResponseStatus.not_bound_wechat);
				rm.setMessage("账户未绑定微信");
				return rm.toJson();
			}else{
				LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
				if(loginAuthority == null){
					rm.setStatus(ResponseStatus.dataError);
					rm.setMessage("授权出现 异常，请与管理员联系");
					return rm.toJson();
				}else{
					String md5Pwd = "";
					if(StringUtils.isEmpty(customer.getLoginPassword())){
						String pwd=RandomUtils.randomString(6);
						md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
						String loginPassword = DESedeCoder.encrypt(md5Pwd);
						String loginUnionMark = DESedeCoder.encrypt(pwd);
						customer.setLoginPassword(loginPassword);
						customer.setLoginUnionMark(loginUnionMark);
						customer.setModelStatus(ModelStatus.update);
						customerService.applyChange(customer);
					}else{
						md5Pwd = DESedeCoder.decrypt(customer.getLoginPassword());
					}
					
					List<String> params = new ArrayList<String>();
					params.add("id");
					params.add("username");
					params.add("nickname");
					params.add("userIdentity");
					params.add("sex");
					params.add("phone");
					params.add("refereeId");
					params.add("refereeIdentity");
					params.add("region");
					params.add("level");
					params.add("picPath");
					
					rm.setStatus(AppResponseStatus.login_seccess);
					rm.setMessage("登录成功");
					rm.put("signCode", loginAuthority.getSignCode());
					rm.put("expire",loginAuthority.getExpireDate());
					rm.put("password", md5Pwd);
					rm.putObj("customer",customer,params);
					
					return rm.toJson();
				}
				
			}
		}	
	}
	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = boundWechatAndLoginApi)
	@ApiOperation(notes = boundWechatAndLoginApi,httpMethod = "POST",value = "绑定微信并登录")
	public String boundWechatAndLogin(String phone,String unionId,String appOpenId,String nickName,String headImgUrl,String sex,String deviceId,String deviceName){
		//1.进这个接口的情况有两种，客户其他数据齐全，但是缺少appOpenId;
		//2.客户就是完全没绑定微信
		Customer customer = customerService.queryModelByUnionId(unionId);
		ResponseModel rm = new ResponseModel();
		if(customer!=null){
			if(!StringUtils.isEmpty(customer.getPhone())){
				//如果客户数据库的号码与目前登陆的相同并且用户的appOpenId为空,说明客户只缺少appOpenId这个信息
				if(phone.equals(customer.getPhone())&&StringUtils.isEmpty(customer.getAppOpenId())){
					customer.setAppOpenId(appOpenId);
					String md5Pwd = "";
					if(StringUtils.isEmpty(customer.getLoginPassword())){
						String pwd=RandomUtils.randomString(6);
						md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
						String loginPassword = DESedeCoder.encrypt(md5Pwd);
						String loginUnionMark = DESedeCoder.encrypt(pwd);
						customer.setLoginPassword(loginPassword);
						customer.setLoginUnionMark(loginUnionMark);
					}else{
						md5Pwd = DESedeCoder.decrypt(customer.getLoginPassword());
					}
					customer.setModelStatus(ModelStatus.update);
					customerService.applyChange(customer);
					
					LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
					if(loginAuthority == null){
						rm.setStatus(ResponseStatus.dataError);
						rm.setMessage("授权出现 异常，请与管理员联系");
						return rm.toJson();
					}else{
							List<String> params = new ArrayList<String>();
							params.add("id");
							params.add("username");
							params.add("nickname");
							params.add("userIdentity");
							params.add("sex");
							params.add("phone");
							params.add("refereeId");
							params.add("refereeIdentity");
							params.add("region");
							params.add("level");
							params.add("picPath");
							
							rm.setStatus(AppResponseStatus.login_seccess);
							rm.setMessage("登录成功");
							rm.put("signCode", loginAuthority.getSignCode());
							rm.put("expire",loginAuthority.getExpireDate());
							rm.put("password", md5Pwd);
							rm.putObj("customer",customer,params);
							
							return rm.toJson();
					}
				}else{
					rm.setStatus(AppResponseStatus.wechat_be_bound_other_account);
					rm.setMessage("此微信号已绑定其他账户");
					return rm.toJson();
				}		
			}else{
				//说明可能是微信过来的，并且没有绑定手机号码
				customer.setPhone(phone);
				customer.setUnionId(unionId);
				customer.setNickname(nickName);
				customer.setLevel(CustomerLevel.vip);
				customer.setPicPath(headImgUrl);
				customer.setAutonym(YesOrNo.no);
				customer.setAppOpenId(appOpenId);
				String defaultSex="女".equals(sex)?"2":"1";
				customer.setSex(defaultSex);
				String md5Pwd = "";
				if(StringUtils.isEmpty(customer.getLoginPassword())){
					String pwd=RandomUtils.randomString(6);
					md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
					String loginPassword = DESedeCoder.encrypt(md5Pwd);
					String loginUnionMark = DESedeCoder.encrypt(pwd);
					customer.setLoginPassword(loginPassword);
					customer.setLoginUnionMark(loginUnionMark);
				}else{
					md5Pwd = DESedeCoder.decrypt(customer.getLoginPassword());
				}
				customer.setModelStatus(ModelStatus.update);
				customerService.applyChange(customer);
				LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
				if(loginAuthority == null){
					rm.setStatus(ResponseStatus.dataError);
					rm.setMessage("授权出现 异常，请与管理员联系");
					return rm.toJson();
				}else{
						List<String> params = new ArrayList<String>();
						params.add("id");
						params.add("username");
						params.add("nickname");
						params.add("userIdentity");
						params.add("sex");
						params.add("phone");
						params.add("refereeId");
						params.add("refereeIdentity");
						params.add("region");
						params.add("level");
						params.add("picPath");
						
						rm.setStatus(AppResponseStatus.login_seccess);
						rm.setMessage("登录成功");
						rm.put("signCode", loginAuthority.getSignCode());
						rm.put("expire",loginAuthority.getExpireDate());
						rm.put("password", md5Pwd);
						rm.putObj("customer",customer,params);
						
						return rm.toJson();
				}	
			}			
		}else{
			//判断是不是来自于海报邀请
			customer = customerService.queryModelByPhone(phone);
			if(customer==null){
				customer = new Customer();
				customer.setId(CommonUtils.getKeyId());
				customer.setPhone(phone);
				customer.setRegistDate(DateUtils.getCurrent());
				int userIdentity = customerService.queryMaxUserIdentity();
				if (userIdentity < 2000) {
					userIdentity = 2000;
				}
				userIdentity++;
				customer.setUserIdentity(userIdentity);
				customer.setModelStatus(ModelStatus.add);
			}else{
				customer.setModelStatus(ModelStatus.update);
			}
			customer.setNickname(ChineseUtils.replaceEmoji(nickName));
			customer.setLevel(CustomerLevel.vip);
			customer.setPicPath(headImgUrl);
			customer.setAutonym(YesOrNo.no);
			customer.setUnionId(unionId);
			customer.setAppOpenId(appOpenId);
			String md5Pwd = "";
			String pwd=RandomUtils.randomString(6);
			md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
			String loginPassword = DESedeCoder.encrypt(md5Pwd);
			String loginUnionMark = DESedeCoder.encrypt(pwd);
			customer.setLoginPassword(loginPassword);
			customer.setLoginUnionMark(loginUnionMark);
			String defaultSex="女".equals(sex)?"2":"1";
			customer.setSex(defaultSex);
			
			if(customerService.applyChange(customer)){
				if(!accountInfoService.addAccountInfo(customer)){
					//添加账户失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addAccount failed" + "添加账户失败");
				};
				if(!goldenBeanInfoService.addGoldenBeanInfo(customer)){
					//添加账户金豆表失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addGoldenBeanInfo failed" + "添加金豆账户失败");
				};
				if(!incomeInfoService.addIncomeInfo(customer)){
					//添加账户奖金表失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addIncomeInfo failed" + "添加奖金账户失败");
				};	
			}	
			LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
			if(loginAuthority == null){
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("授权出现 异常，请与管理员联系");
				return rm.toJson();
			}else{
		
				List<String> params = new ArrayList<String>();
				params.add("id");
				params.add("username");
				params.add("nickname");
				params.add("userIdentity");
				params.add("sex");
				params.add("phone");
				params.add("refereeId");
				params.add("refereeIdentity");
				params.add("region");
				params.add("level");
				params.add("picPath");
				
				rm.setStatus(AppResponseStatus.login_seccess);
				rm.setMessage("登录成功");
				rm.put("signCode", loginAuthority.getSignCode());
				rm.put("expire",loginAuthority.getExpireDate());
				rm.put("password", md5Pwd);
				rm.putObj("customer",customer,params);
				
				return rm.toJson();
			}	
			
		}
	}

	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = thirdpartyLoginApi)
	@ApiOperation(notes = thirdpartyLoginApi,httpMethod = "POST",value = "微信第三方登录")
	public String thirdpartyLogin(String unionId,String appOpenId,String deviceId,String deviceName){
		ResponseModel rm = new ResponseModel();
		Customer customer = customerService.queryModelByUnionId(unionId);
		if(customer!=null){
			if(!StringUtils.isEmpty(customer.getPhone())){
				LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
				rm.setStatus(AppResponseStatus.login_seccess);
				rm.setMessage("登陆成功");
				String md5Pwd = "";
				if(StringUtils.isEmpty(customer.getLoginPassword())){
					String pwd=RandomUtils.randomString(6);
					md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
					String loginPassword = DESedeCoder.encrypt(md5Pwd);
					String loginUnionMark = DESedeCoder.encrypt(pwd);
					customer.setLoginPassword(loginPassword);
					customer.setLoginUnionMark(loginUnionMark);
				}else{
					md5Pwd = DESedeCoder.decrypt(customer.getLoginPassword());
				}
				customer.setAppOpenId(appOpenId);
				customer.setModelStatus(ModelStatus.update);
				customerService.applyChange(customer);
				
				List<String> params = new ArrayList<String>();
				params.add("id");
				params.add("username");
				params.add("nickname");
				params.add("userIdentity");
				params.add("sex");
				params.add("phone");
				params.add("refereeId");
				params.add("refereeIdentity");
				params.add("region");
				params.add("level");
				params.add("picPath");
				
				rm.setStatus(AppResponseStatus.login_seccess);
				rm.setMessage("登录成功");
				rm.put("signCode", loginAuthority.getSignCode());
				rm.put("expire",loginAuthority.getExpireDate());
				rm.put("password", md5Pwd);
				rm.putObj("customer",customer,params);
				
				return rm.toJson();
			}else{
				rm.setStatus(AppResponseStatus.not_bound_phone);
				rm.setMessage("账户未绑定电话");
				return rm.toJson();
			}
		}else{
			rm.setStatus(AppResponseStatus.not_bound_phone);
			rm.setMessage("账户未绑定电话");
			return rm.toJson();
		}
	}
	
	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = boundPhoneAndLoginApi)
	@ApiOperation(notes = boundPhoneAndLoginApi,httpMethod = "POST",value = "绑定手机并登录")
	public String boundPhoneAndLogin(String phone,String code,String appOpenId,String unionId,String nickName,String headImgUrl,String sex,String deviceId,String deviceName){
		ResponseModel rm = new ResponseModel();
		ICached cached = CommonApplicationContextUtil.getCurrentContext().getBean(ICached.class);
		String matchCode = String.valueOf(cached.get(phone+"verifyCode"));
		String matchPhone = String.valueOf(cached.get(phone));
		Date sendTime = (Date)cached.get(phone+"sendTime");
		
		
		if(sendTime!=null){
			if(DateUtils.getCurrent().getTime()-sendTime.getTime()>5*60*1000){
				rm.setStatus(AppResponseStatus.code_expire);
				rm.setMessage("验证码已过期");
				return rm.toJson();
			}
		}	
		
		if(!(code.equals(matchCode) && phone.equals(matchPhone))){
			rm.setStatus(AppResponseStatus.code_data_error);
			rm.setMessage("验证码错误");
			return rm.toJson();
		}

		cached.remove(phone+"verifyCode");
		cached.remove(phone+"sendTime");
		
		Customer customer = customerService.queryModelByPhone(phone);
		
		if(customer!=null){
			if(StringUtils.isEmpty(customer.getUnionId())){
				//说明可能是海报过来的
				customer.setNickname(ChineseUtils.replaceEmoji(nickName));
				customer.setLevel(CustomerLevel.vip);
				customer.setPicPath(headImgUrl);
				customer.setAutonym(YesOrNo.no);
				customer.setUnionId(unionId);
				customer.setAppOpenId(appOpenId);
				String md5Pwd = "";
				String pwd=RandomUtils.randomString(6);
				md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
				String loginPassword = DESedeCoder.encrypt(md5Pwd);
				String loginUnionMark = DESedeCoder.encrypt(pwd);
				customer.setLoginPassword(loginPassword);
				customer.setLoginUnionMark(loginUnionMark);
				String defaultSex="女".equals(sex)?"2":"1";
				customer.setSex(defaultSex);
				customer.setModelStatus(ModelStatus.update);
				if(customerService.applyChange(customer)){
					if(!accountInfoService.addAccountInfo(customer)){
						//添加账户失败，抛出运行时异常
						throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addAccount failed" + "添加账户失败");
					};
					if(!goldenBeanInfoService.addGoldenBeanInfo(customer)){
						//添加账户金豆表失败，抛出运行时异常
						throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addGoldenBeanInfo failed" + "添加金豆账户失败");
					};
					if(!incomeInfoService.addIncomeInfo(customer)){
						//添加账户奖金表失败，抛出运行时异常
						throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addIncomeInfo failed" + "添加奖金账户失败");
					};	
				}
			
				LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
				if(loginAuthority == null){
					rm.setStatus(ResponseStatus.dataError);
					rm.setMessage("授权出现 异常，请与管理员联系");
					return rm.toJson();
				}else{
					List<String> params = new ArrayList<String>();
					params.add("id");
					params.add("username");
					params.add("nickname");
					params.add("userIdentity");
					params.add("sex");
					params.add("phone");
					params.add("refereeId");
					params.add("refereeIdentity");
					params.add("region");
					params.add("level");
					params.add("picPath");
					
					rm.setStatus(AppResponseStatus.login_seccess);
					rm.setMessage("登录成功");
					rm.put("signCode", loginAuthority.getSignCode());
					rm.put("expire",loginAuthority.getExpireDate());
					rm.put("password", md5Pwd);
					rm.putObj("customer",customer,params);
					
					return rm.toJson();
				}	
			}else{
				rm.setStatus(AppResponseStatus.phone_be_bound_other_account);
				rm.setMessage("电话已经被别的账户绑定");
				return rm.toJson();
			}
			
		}else{
			customer = new Customer();
			customer.setId(CommonUtils.getKeyId());
			customer.setNickname(ChineseUtils.replaceEmoji(nickName));
			customer.setPhone(phone);
			customer.setRegistDate(DateUtils.getCurrent());
			customer.setLevel(CustomerLevel.vip);
			customer.setPicPath(headImgUrl);
			customer.setAutonym(YesOrNo.no);
			customer.setUnionId(unionId);
			customer.setAppOpenId(appOpenId);
			String md5Pwd = "";
			String pwd=RandomUtils.randomString(6);
			md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
			String loginPassword = DESedeCoder.encrypt(md5Pwd);
			String loginUnionMark = DESedeCoder.encrypt(pwd);
			customer.setLoginPassword(loginPassword);
			customer.setLoginUnionMark(loginUnionMark);
			String defaultSex="女".equals(sex)?"2":"1";
			customer.setSex(defaultSex);
			
			int userIdentity = customerService.queryMaxUserIdentity();
			if (userIdentity < 2000) {
				userIdentity = 2000;
			}
			userIdentity++;
			customer.setUserIdentity(userIdentity);
			if(customerService.addModel(customer)){
				if(!accountInfoService.addAccountInfo(customer)){
					//添加账户失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addAccount failed" + "添加账户失败");
				};
				if(!goldenBeanInfoService.addGoldenBeanInfo(customer)){
					//添加账户金豆表失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addGoldenBeanInfo failed" + "添加金豆账户失败");
				};
				if(!incomeInfoService.addIncomeInfo(customer)){
					//添加账户奖金表失败，抛出运行时异常
					throw new DaoBaseRuntimeException("CustomerServiceImpl.addCustomer.addIncomeInfo failed" + "添加奖金账户失败");
				};	
			}	
			LoginAuthority loginAuthority = loginAuthorityService.saveLoginAuthority(customer.getId(),customer.getUsername(), deviceId, deviceName);
			if(loginAuthority == null){
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("授权出现 异常，请与管理员联系");
				return rm.toJson();
			}else{
				List<String> params = new ArrayList<String>();
				params.add("id");
				params.add("username");
				params.add("nickname");
				params.add("userIdentity");
				params.add("sex");
				params.add("phone");
				params.add("refereeId");
				params.add("refereeIdentity");
				params.add("region");
				params.add("level");
				params.add("picPath");
				
				rm.setStatus(AppResponseStatus.login_seccess);
				rm.setMessage("登录成功");
				rm.put("signCode", loginAuthority.getSignCode());
				rm.put("expire",loginAuthority.getExpireDate());
				rm.put("password", md5Pwd);
				rm.putObj("customer",customer,params);
				
				return rm.toJson();
			}	
		}
	}
	
	/**
	 * String username
	 * String phone
	 * String refereeId
	 * String refereeIdentity
	 * String password
	 * 
	 * */
	
	@ResponseBody
	@RequestMapping(value = updateLevelApi)
	@ApiOperation(notes = updateLevelApi,httpMethod = "POST",value = "更新等级")
	public String updateLevel(String tradeNo,String username,Integer refereeIdentity,String refereeId,String region,String password){	
		Customer customer = new Customer();
		customer.setId(getLoginId());
		customer.setUsername(username);
		customer.setRefereeId(refereeId);
		customer.setRefereeIdentity(refereeIdentity);
		customer.setRegion(region);
		customer.setPassword(password);
		ResponseModel rm = new ResponseModel();
				
		if(!StringUtils.isEmpty(tradeNo)){
			WechatOrder wechatOrder = wechatOrderService.queryModel(tradeNo);
			if(StringUtils.isEmpty(wechatOrder)){
				rm.setStatus(AppResponseStatus.order_not_exist);
				rm.setMessage("订单不存在");
				return rm.toJson();
			}else{
				if(!WechatOrderStatus.paySuccess.equals(wechatOrder.getOrderStatus())){
					rm.setStatus(AppResponseStatus.non_payment);
					rm.setMessage("未完成付款");
					return rm.toJson();
				}else{	
					String orderId=wechatOrder.getTradeNo();
					WechatOrderGoodsSearch search=new WechatOrderGoodsSearch();
					search.setOrderId(orderId);
					List<WechatOrderGoods> wechatOrderGoods=wechatOrderGoodsService.queryList(search);
					
					if(!StringUtils.isEmpty(customer.getOpenId())){
						//发送订单通知
						//sendJoinRedEnvelopeRecord(customer, refereeCustomer, wechatOrder);
						WechatTemplateManager.sendOrderPaySuccess(wechatOrder.getOpenId(), wechatOrder.getTotalFee(), wechatOrder.getName(),null);
					}
					
					Customer currentCustomer=new Customer();
					currentCustomer=customerService.queryModel(getLoginId());
					//APP发送订单通知(给当前人)
					JpushClient.sendorderPaySuccessApp(wechatOrder.getTotalFee(), currentCustomer,appRemindMessageService);
					
					boolean maker=Enumerable.init(wechatOrderGoods).any(wog->{return GoodsMark.maker.equals(wog.getGoodsMark());});
					if(maker){
						customer.setLevel(CustomerLevel.maker);
						customer.setJoinMakerDate(DateUtils.getCurrent());
						Customer firstcustomer=new Customer();
						if(refereeId != null){
							firstcustomer=customerService.queryModel(refereeId);
						}
						if(firstcustomer != null && AttentionStatus.attention.equals(firstcustomer.getAttentionStatus())){
							
							String id="";
							//生成红包
							RedEnvelopeRecord redEnvelopeRecord  = redEnvelopeRecordService.queryModelByCategory(firstcustomer.getId(), customer.getId(), firstcustomer.getId(),RedEnvelopeRecordType.recommendMaker);
							
							if(redEnvelopeRecord==null){
								double redMoney=0.0;
								redEnvelopeRecord = new RedEnvelopeRecord();
								String redEnvelopeRecordId = CommonUtils.getKeyId(); 				
								redEnvelopeRecord.setId(redEnvelopeRecordId);
								redEnvelopeRecord.setReceiverId(firstcustomer.getId());
								redEnvelopeRecord.setRefreeId(firstcustomer.getId());
								redEnvelopeRecord.setRefreeLevel(firstcustomer.getLevel());
								redEnvelopeRecord.setJoinId(currentCustomer.getId());
								redEnvelopeRecord.setJoinLevel(CustomerLevel.maker);
								/*初创推荐初创*/
								if(CustomerLevel.maker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToMaker");
									redMoney = wp.getParam();
								}
								/*高创推荐初创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToMaker");
									redMoney = wp.getParam();
								}
								/*合伙人推荐初创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel()) && "city".equals(firstcustomer.getHonor())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToMaker");
									redMoney = wp.getParam();
								}
								
								/*double redMoney = getRedEnvelope(RedEnvelopeRecordType.recommendMaker);
								redEnvelopeRecord.setRedMoney(redMoney);*/
								redEnvelopeRecord.setRedMoney(redMoney);
								redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
								redEnvelopeRecord.setCategory(RedEnvelopeRecordType.recommendMaker);
								redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
								redEnvelopeRecord.setTradeNo(wechatOrder.getTradeNo());
								redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
								redEnvelopeRecord.setModelStatus(ModelStatus.add);
								
								if(redEnvelopeRecordService.applyChange(redEnvelopeRecord)){
									id = redEnvelopeRecordId;
								}
						}
							if(CustomerLevel.maker.equals(firstcustomer.getLevel())||CustomerLevel.highMaker.equals(firstcustomer.getLevel())){
								
								//APP发送通知（给当前登录人的上一级）
								JpushClient.sendUpdateLevelApp(firstcustomer.getUserIdentity(), currentCustomer, firstcustomer, null, id, appRemindMessageService,CustomerLevel.maker);
								if(!StringUtils.isEmpty(firstcustomer.getOpenId())){
									WechatTemplateManager.sendUpdateLevel(firstcustomer.getOpenId(), currentCustomer,CustomerLevel.maker,null,id);
								}
							}
							Customer secondCustomer=new Customer();
							if(!StringUtils.isEmpty(firstcustomer.getRefereeId())){
								secondCustomer=customerService.queryModel(firstcustomer.getRefereeId());
							}
							if(secondCustomer != null && AttentionStatus.attention.equals(secondCustomer.getAttentionStatus())){
								
								if(CustomerLevel.maker.equals(secondCustomer.getLevel())||CustomerLevel.highMaker.equals(secondCustomer.getLevel())){
									
									//APP发送通知（给当前登录人的上二级）
									JpushClient.sendUpdateLevelApp(secondCustomer.getUserIdentity(), currentCustomer, firstcustomer, secondCustomer,null,appRemindMessageService,CustomerLevel.maker);								
									if(!StringUtils.isEmpty(secondCustomer.getOpenId())){
										WechatTemplateManager.sendUpdateLevel(secondCustomer.getOpenId(), currentCustomer,CustomerLevel.maker,firstcustomer,null);
									}
								}
							}
					    }		
					}
					boolean highMaker=Enumerable.init(wechatOrderGoods).any(wog->{return GoodsMark.highMaker.equals(wog.getGoodsMark());});
					if(highMaker){
						customer.setLevel(CustomerLevel.highMaker);
						customer.setJoinHighMakerDate(DateUtils.getCurrent());
						Customer firstcustomer=new Customer();
						if(refereeId != null){
							firstcustomer=customerService.queryModel(refereeId);
						}
						if(firstcustomer != null && AttentionStatus.attention.equals(firstcustomer.getAttentionStatus())){
							String id="";
							String category = "";
							double redMoney=0.0;
							if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.joinHighmakerMoney){
								category = RedEnvelopeRecordType.recommendHighmaker;
								/*初创推荐高创*/
								if(CustomerLevel.maker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToHighMaker");
									redMoney = wp.getParam();
								}
								/*高创推荐高创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToHighMaker");
									redMoney = wp.getParam();
								}
								/*合伙人推荐高创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel()) && "city".equals(firstcustomer.getHonor())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToHighMaker");
									redMoney = wp.getParam();
								}
							}else if(wechatOrder.getTotalFee()==RedEnvelopeRecordType.makerToHighmakerMoney){
								category = RedEnvelopeRecordType.makerToHighmaker;
								if(CustomerLevel.maker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("makerToMakerToHighMaker");
									redMoney = wp.getParam();
								}
								/*高创推荐高创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("highMakerToMakerToHighMaker");
									redMoney = wp.getParam();
								}
								/*合伙人推荐高创*/
								if(CustomerLevel.highMaker.equals(firstcustomer.getLevel()) && "city".equals(firstcustomer.getHonor())){
									WithdrawParam wp = withdrawParamService.queryModelByHelpCode("cityToMakerToHighMaker");
									redMoney = wp.getParam();
								}
							}
							RedEnvelopeRecord redEnvelopeRecord  = redEnvelopeRecordService.queryModelByCategory(firstcustomer.getId(), currentCustomer.getId(), firstcustomer.getId(),category);
							if(redEnvelopeRecord==null){
								redEnvelopeRecord = new RedEnvelopeRecord();
								String redEnvelopeRecordId = CommonUtils.getKeyId(); 				
								redEnvelopeRecord.setId(redEnvelopeRecordId);
								redEnvelopeRecord.setReceiverId(firstcustomer.getId());
								redEnvelopeRecord.setRefreeId(firstcustomer.getId());
								redEnvelopeRecord.setRefreeLevel(firstcustomer.getLevel());
								redEnvelopeRecord.setJoinId(currentCustomer.getId());
								redEnvelopeRecord.setJoinLevel(CustomerLevel.highMaker);
								redEnvelopeRecord.setRedMoney(redMoney);
								redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
								redEnvelopeRecord.setCategory(category);
								redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
								redEnvelopeRecord.setTradeNo(wechatOrder.getTradeNo());
								redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
								redEnvelopeRecord.setModelStatus(ModelStatus.add);
								
								if(redEnvelopeRecordService.applyChange(redEnvelopeRecord)){
									id = redEnvelopeRecordId;
								}	
							}
							if(CustomerLevel.maker.equals(firstcustomer.getLevel())||CustomerLevel.highMaker.equals(firstcustomer.getLevel())){
								//APP发送通知（给当前登录人的上一级）
								JpushClient.sendUpdateLevelApp(firstcustomer.getUserIdentity(), currentCustomer, firstcustomer, null, id, appRemindMessageService,CustomerLevel.highMaker);
								if(!StringUtils.isEmpty(firstcustomer.getOpenId())){
									WechatTemplateManager.sendUpdateLevel(firstcustomer.getOpenId(), currentCustomer,CustomerLevel.maker,null,id);
								}
							}
							Customer secondCustomer=new Customer();
							if(!StringUtils.isEmpty(firstcustomer.getRefereeId())){
								secondCustomer=customerService.queryModel(firstcustomer.getRefereeId());
							}
							if(secondCustomer != null && AttentionStatus.attention.equals(secondCustomer.getAttentionStatus())){
								
								if(CustomerLevel.maker.equals(secondCustomer.getLevel())||CustomerLevel.highMaker.equals(secondCustomer.getLevel())){
									
									//APP发送通知（给当前登录人的上二级）
									JpushClient.sendUpdateLevelApp(secondCustomer.getUserIdentity(), currentCustomer, firstcustomer, secondCustomer,null,appRemindMessageService,CustomerLevel.maker);								
									if(!StringUtils.isEmpty(secondCustomer.getOpenId())){
										WechatTemplateManager.sendUpdateLevel(secondCustomer.getOpenId(), currentCustomer,CustomerLevel.highMaker,firstcustomer,null);
									}
								}
							}		
						}
					}
					if(!StringUtils.isEmpty(customer.getPassword())){
						String pwd=customer.getPassword();
						String md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
						customer.setPassword(DESedeCoder.encrypt(md5Pwd));
						customer.setUnionMark(DESedeCoder.encrypt(pwd));
					}
					if(!StringUtils.isEmpty(customer.getRegion())){
						customer.setUpdateRegionDate(DateUtils.getCurrent());
					}
					
					boolean result=customerService.updateCustomerByJoinMaker(customer);
					if(result){
						rm.setStatus(ResponseStatus.success);
						rm.setMessage("ok");
						rm.put("result", true);
						return rm.toJson();
					}else{
						rm.setStatus(ResponseStatus.success);
						rm.setMessage("失败");
						rm.put("result", false);
						return rm.toJson();
					}				
				}
			}
			
		}else{
			rm.setStatus(AppResponseStatus.order_not_exist);
			rm.setMessage("订单不存在");
			return rm.toJson();
		}
	}
	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = checkInviteCodeApi)
	@ApiOperation(notes = checkInviteCodeApi,httpMethod = "POST",value = "判断邀请码是否正确")
	public String checkInviteCode(String phone){
		ResponseModel rm = new ResponseModel();
		
		if("4000858118".equals(phone)){
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("邀请人号码为官方号码");
			rm.put("result", true);
			rm.put("refereeId", null);
			rm.put("refereeIdentity", 1);
			return rm.toJson();
		}
		
		Customer customer = customerService.queryModelByPhone(phone);
		
		if(customer==null){
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("邀请人号码不存在");
			rm.put("result", false);
		}else{
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("邀请人号码存在");
			rm.put("result", true);
			rm.put("phone", phone);
			rm.put("refereeId", customer.getId());
			rm.put("refereeIdentity", customer.getUserIdentity());
			
			
			
		}
		
		return rm.toJson();
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = retrievePasswordApi)
	@ApiOperation(notes = retrievePasswordApi,httpMethod = "POST",value = "找回支付密码")
	public String retrievePassword(String phone,String code,String newPassword){
		ResponseModel rm = new ResponseModel();
		ICached cached = CommonApplicationContextUtil.getCurrentContext().getBean(ICached.class);
		String matchCode = String.valueOf(cached.get(phone+"verifyCode"));
		String matchPhone = String.valueOf(cached.get(phone));
		Date sendTime = (Date)cached.get(phone+"sendTime");
		
		
		if(sendTime!=null){
			if(DateUtils.getCurrent().getTime()-sendTime.getTime()>5*60*1000){
				rm.setStatus(AppResponseStatus.code_expire);
				rm.setMessage("验证码已过期");
				return rm.toJson();
			}
		}	
		
		if(!(code.equals(matchCode) && phone.equals(matchPhone))){
			rm.setStatus(AppResponseStatus.code_data_error);
			rm.setMessage("验证码错误");
			return rm.toJson();
		}

		cached.remove(phone+"verifyCode");
		cached.remove(phone+"sendTime");
		
		if(!StringUtils.isEmpty(newPassword)){
			String pwd=newPassword;
			String md5Pwd=MD5Utils.encoderByMd5With32Bit(pwd);
			String password = DESedeCoder.encrypt(md5Pwd);
			String unionMark = DESedeCoder.encrypt(pwd);
			if(customerService.updatePassword(password, getLoginId(), unionMark)){
				rm.setStatus(ResponseStatus.success);
				rm.setMessage("密码修改成功");
				rm.put("result", true);
			}else{
				rm.setStatus(ResponseStatus.success);
				rm.setMessage("服务器出错");
				rm.put("result", false);
			}	
		}
		return rm.toJson();
	}
}
